#include "stdafx.h"
#include <string> 
#include "MHNetwork.h"
#include "../cMainState.h"
bool bReceiving = FALSE;		
CMHNetwork* gNetwork = NULL;
HMODULE g_hBaseNetworkHandle = NULL;
CMHNetwork::CMHNetwork()
{
	m_ConnectionIndex = NULL;
	gNetwork = this;
	m_bDisconnecting = FALSE;
	m_CheckSum = 0;
}

CMHNetwork::~CMHNetwork()
{

	Release();
}
void CMHNetwork::SetState(cMainState* t)
{
	MyChat = t;
	m_RecvedDataSize=0;	
	m_RecvCount=0;
}
void CMHNetwork::Release()

{
	if(m_pBaseNetwork)
	{
		Disconnect();
	}
	
	SAFE_RELEASE(m_pBaseNetwork);


	if(g_hBaseNetworkHandle)
	{
		FreeLibrary( g_hBaseNetworkHandle );
		g_hBaseNetworkHandle = NULL;
	}

}

BOOL CMHNetwork::Init(HWND hWnd)
{
	m_hMainWnd = hWnd;
	
	HRESULT hr;
	
	g_hBaseNetworkHandle = LoadLibraryA("BaseNetwork.dll");
	DllGetClassObject_BaseNetwork	pNetFunc;
	pNetFunc = (DllGetClassObject_BaseNetwork)GetProcAddress(g_hBaseNetworkHandle,"DllGetClassObject");
	hr = pNetFunc(CLSID_SC_BASENETWORK_DLL, IID_SC_BASENETWORK_DLL, (void**)&m_pBaseNetwork);		
	if (hr != S_OK)
	{
		MessageBoxA(NULL,"BASENETWORK.DLL is Not Exist.","Error",MB_OK);
		return FALSE;
	}
	
	DESC_BASENETWORK Desc;	memset(&Desc,0,sizeof(Desc));
	Desc.wSockEventWinMsgID = WM_SOCKEVENTMSG;	
	Desc.OnConnect			= OnCon;
	Desc.OnDisconnect		= OnDisCon;
	Desc.ReceivedMsg		= OnRecv;
	
	m_pBaseNetwork->InitNetwork(m_hMainWnd,5,&Desc);

	if(m_pBaseNetwork == NULL)
		return FALSE;

	
	return TRUE;
}


BOOL CMHNetwork::ConnectToServer(char* ip,WORD port)
{	
	m_ConnectionIndex = m_pBaseNetwork->ConnectToServer(ip,port);
	if(!m_ConnectionIndex)
		return FALSE;
	
	return TRUE;
}
void CMHNetwork::Disconnect()
{
	if(m_ConnectionIndex)
	{
		m_pBaseNetwork->CompulsiveDisconnect(m_ConnectionIndex);
		m_ConnectionIndex = 0;	
		m_bDisconnecting = TRUE;
	}
}


void CMHNetwork::Send(MSGROOT* pMsg,int MsgLen)
{
	pMsg->CheckSum = m_CheckSum++;
//	pMsg->Code = 2;
	if(m_ConnectionIndex)
	{  
		m_pBaseNetwork->Send(m_ConnectionIndex,(char*)pMsg,MsgLen);
	}

}

//////////////////////////////////////////////////////////////////////////


void OnCon(DWORD dwConIndex)
{

}

void OnDisCon(DWORD dwConIndex)
{
	if(gNetwork->m_bDisconnecting == FALSE)
	{
		gNetwork->m_MianDlg->OnDisconnect();
	}
	else
	{
		gNetwork->m_bDisconnecting = FALSE;
	}
}

CMHNetwork& CMHNetwork::getinstance()
{
	static CMHNetwork Network;
	return Network;
}
void OnRecv(DWORD dwConIndex,char* pMsg,DWORD msglen)
{	
	MSGROOT* pTemp = (MSGROOT*)pMsg;
	gNetwork->MyChat->NetworkMsgParse(pTemp->Category,pTemp->Protocol,pMsg);
	bReceiving = FALSE;
}




